<template>
  <div class="search-bar">
    <el-input
      v-model="searchName"
      placeholder="请输入名称搜索"
      style="width: 220px; margin-right: 10px"
    />
    <el-button type="primary" color="#203A64" @click="handleQuery">查询</el-button>
    <el-button @click="handleReset">重置</el-button>
  </div>

  <!-- 操作按钮区域 -->
  <div class="action-buttons">
    <el-button type="primary" color="#203A64" @click="addzz">新增组织</el-button>
    <el-button>批量导入</el-button>
    <el-button>组织变更</el-button>
  </div>

  <!-- PC端表格 -->
  <el-table
    v-if="!isMobile"
    :data="pagedData"
    border
    style="width: 100%; margin-top: 16px"
  >
    <el-table-column prop="department" label="名称" />
    <el-table-column prop="typeOfOrganization" label="组织类型" />
    <el-table-column prop="DepartmentHead" label="部门负责人" />
    <el-table-column prop="OrganizationCode" label="组织编码" />
    <el-table-column prop="authorizedStaffCount" label="编制人数" />
    <el-table-column prop="activeStaffCount" label="在职人数" />
    <el-table-column label="操作">
      <template #default="scope">
        <el-button
          :link="true"
          size="small"
          @click="handleEdit(scope.row)"
          style="color: #203a64"
          >编辑</el-button
        >
        <!-- 添加删除事件绑定 -->
        <el-button
          :link="true"
          size="small"
          style="color: #203a64"
          @click="handleDelete(scope.row)"
          >删除</el-button
        >
      </template>
    </el-table-column>
  </el-table>

  <!-- 移动端卡片式列表 -->
  <div v-else>
    <div v-for="row in pagedData" :key="row.id" class="mobile-card">
      <div class="mobile-row">
        <span class="mobile-label">名称：</span>
        <span>{{ row.department }}</span>
      </div>
      <div class="mobile-row">
        <span class="mobile-label">组织类型：</span>
        <span>{{ row.typeOfOrganization }}</span>
      </div>
      <div class="mobile-row">
        <span class="mobile-label">负责人：</span>
        <span>{{ row.DepartmentHead }}</span>
      </div>
      <div class="mobile-row mobile-actions">
        <el-button size="small" @click="showDetail(row)">详情</el-button>
        <el-button size="small" @click="handleEdit(row)">编辑</el-button>
        <el-button
          size="small"
          type="danger"
          @click="handleDelete(row)"
          class="delete-button"
          >删除</el-button
        >
      </div>
    </div>
  </div>

  <!-- 底部分页区域 -->
  <div class="pagination" :class="{ 'mobile-pagination': isMobile }">
    <el-pagination
      background
      layout="prev, pager, next, sizes"
      :total="tableData.length"
      :page-size="pageSize"
      :current-page="currentPage"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
      :small="isMobile"
      :page-sizes="[5, 10, 20, 50]"
      :style="
        isMobile
          ? 'width: 100%; overflow-x: auto; font-size: 15px; padding: 4px 0;color: #203A64;'
          : ''
      "
    />
  </div>

  <!-- 编辑弹窗 -->
  <el-dialog
    title="编辑组织"
    v-model="editDialogVisible"
    :width="isMobile ? '95vw' : '500px'"
    :style="isMobile ? 'min-width: unset; max-width: 100vw;' : ''"
    @close="handleCancel"
  >
    <el-form :model="form" :rules="rules" ref="editFormRef" label-width="100px">
      <!-- 组织名称（统一为 departments） -->
      <el-form-item label="组织名称" prop="department">
        <el-input v-model="form.department" placeholder="请输入" />
      </el-form-item>
      <!-- 组织类型（新增，与添加弹窗一致） -->
      <el-form-item label="组织类型" prop="typeOfOrganization">
        <el-select v-model="form.typeOfOrganization" placeholder="请选择">
          <el-option label="部门" value="部门" />
          <el-option label="子公司" value="子公司" />
        </el-select>
      </el-form-item>
      <!-- 组织负责人（统一为 DepartmentHead，输入框） -->
      <el-form-item label="组织负责人" prop="DepartmentHead">
        <el-input v-model="form.DepartmentHead" placeholder="请输入" />
      </el-form-item>
      <!-- 编制人数（统一为 authorizedStaffCount） -->
      <el-form-item label="编制人数" prop="authorizedStaffCount">
        <el-input v-model="form.authorizedStaffCount" placeholder="请输入" />
      </el-form-item>
      <!-- 在职人数（统一为 activeStaffCount） -->
      <el-form-item label="在职人数" prop="activeStaffCount">
        <el-input v-model="form.activeStaffCount" placeholder="请输入" />
      </el-form-item>
      <!-- 操作按钮（保持不变） -->
      <el-form-item>
        <div class="dialog-footer-right">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确认</el-button>
        </div>
      </el-form-item>
    </el-form>
  </el-dialog>
  <!-- 添加弹窗 -->
  <el-dialog
    v-model="addDialogVisible"
    title="添加部门"
    :width="isMobile ? '95vw' : '500px'"
    :style="isMobile ? 'min-width: unset; max-width: 100vw;' : ''"
    align-center
  >
    <el-form :model="form1" :rules="rules" ref="addFormRef" label-width="100px">
      <el-form-item label="组织名称" prop="department">
        <el-input v-model="form1.department" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="组织类型" prop="typeOfOrganization">
        <el-select v-model="form1.typeOfOrganization" placeholder="请选择">
          <el-option label="部门" value="部门" />
          <el-option label="子公司" value="子公司" />
        </el-select>
      </el-form-item>
      <el-form-item label="组织负责人" prop="DepartmentHead">
        <el-input v-model="form1.DepartmentHead" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="编制人数" prop="authorizedStaffCount">
        <el-input v-model="form1.authorizedStaffCount" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="在职人数" prop="activeStaffCount">
        <el-input v-model="form1.activeStaffCount" placeholder="请输入" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleAddCancel">取消</el-button>
        <el-button type="primary" @click="handleAddSubmit" color="#203A64"
          >确认</el-button
        >
      </div>
    </template>
  </el-dialog>

  <!-- 弹窗：详情/编辑 -->
  <el-dialog
    v-model="dialogVisible"
    title="详情/编辑"
    :width="isMobile ? '95vw' : '90vw'"
    :style="isMobile ? 'min-width: unset; max-width: 100vw;' : ''"
    :close-on-click-modal="false"
  >
    <el-form :model="currentRow" label-width="80px">
      <el-form-item label="名称"
        ><el-input v-model="currentRow.department"
      /></el-form-item>
      <el-form-item label="组织类型"
        ><el-input v-model="currentRow.typeOfOrganization"
      /></el-form-item>
      <el-form-item label="负责人"
        ><el-input v-model="currentRow.DepartmentHead"
      /></el-form-item>
      <el-form-item label="编制人数"
        ><el-input v-model="currentRow.authorizedStaffCount"
      /></el-form-item>
      <el-form-item label="在职人数"
        ><el-input v-model="currentRow.activeStaffCount"
      /></el-form-item>
      <!-- 可根据需要添加更多字段 -->
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">关闭</el-button>
      <el-button type="primary" @click="saveEdit">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, computed } from "vue";
import type { FormRules, FormInstance } from "element-plus";

import {
  getDepartments,
  addDepartment,
  updateDepartment,
  getDepartmentsByDepartmentHead,
  deleteDepartment,
} from "../utils/api.js";

const isMobile = ref(window.innerWidth < 1000);
const handleResize = () => {
  isMobile.value = window.innerWidth < 1000;
};
onMounted(() => window.addEventListener("resize", handleResize));
onUnmounted(() => window.removeEventListener("resize", handleResize));

const tabledatas = async () => {
  try {
    const res = await getDepartments();
    console.log(res.data);
    tableData.value = res.data;
    console.log(tableData.value);
  } catch (error) {
    console.error("获取部门数据失败:", error);
    ElMessage.error("获取部门数据失败，请检查网络连接或后端服务");
    tableData.value = []; // 设置为空数组，避免页面出错
  }
};
onMounted(() => {
  tabledatas();
});
// 表格行数据类型
interface OrgData {
  id: string;
  department: string;
  typeOfOrganization: string;
  DepartmentHead: string;
  authorizedStaffCount: number;
  activeStaffCount: number;
  // 可选字段
  type?: string;
  leader?: string;
  leaders?: string[];
  OrganizationCode?: string;
  quota?: number;
  staff?: number;
  parentOrgName?: string;
  children?: OrgData[];
}

// 模拟表格数据
const tableData = ref<OrgData[]>([]);
// const tableData1=ref<[]>([])
// 弹窗控制
const editDialogVisible = ref(false);
// 添加弹窗控制
const addDialogVisible = ref(false);

const addzz = () => {
  addDialogVisible.value = true;
};
// 表单数据（新增 staff 字段，修复 leaders 类型推断）
const form1 = reactive<Partial<OrgData>>({
  department: "", // 原 orgName 改为 department
  typeOfOrganization: "", // 新增组织类型字段
  DepartmentHead: "", // 原 leaders 改为 DepartmentHead（输入框）
  authorizedStaffCount: undefined, // 原 staffQuota 改为 authorizedStaffCount
  activeStaffCount: undefined, // 原 staff 改为 activeStaffCount
});
// 表单数据（补充组织编码字段）
const form = reactive<Partial<OrgData>>({
  department: "",
  typeOfOrganization: "",
  DepartmentHead: "",
  authorizedStaffCount: undefined,
  activeStaffCount: undefined,
  OrganizationCode: "", // 新增：与 OrgData 中的 OrganizationCode 字段对应
});
// 表单验证规则（与添加弹窗统一）
const rules = reactive<FormRules>({
  department: [{ required: true, message: "请输入组织名称", trigger: "blur" }],
  typeOfOrganization: [{ required: true, message: "请选择组织类型", trigger: "change" }],
  DepartmentHead: [{ required: true, message: "请输入组织负责人", trigger: "blur" }],
  authorizedStaffCount: [
    { required: true, message: "请输入编制人数", trigger: "blur" },
    { pattern: /^\d+$/, message: "请输入有效数字", trigger: "blur" },
  ],
  activeStaffCount: [
    { required: true, message: "请输入在职人数", trigger: "blur" },
    { pattern: /^\d+$/, message: "请输入有效数字", trigger: "blur" },
  ],
});

// 下拉选项数据源

// 表单 Ref
const editFormRef = ref<FormInstance>();

// 点击编辑：赋值当前行数据到表单
// 添加：声明 currentEditCode（原代码可能遗漏此声明）
const currentEditCode = ref<string>("");

// 点击编辑：赋值当前行数据到表单（补充其他字段初始化）
const handleEdit = (row: OrgData) => {
  currentEditCode.value = row.id;
  // 名称
  form.department = row.department;
  // 组织类型（假设 OrgData 中的 type 对应表单的 typeOfOrganization）
  form.typeOfOrganization = row.typeOfOrganization;
  // 负责人（假设 OrgData 中的 leader 对应表单的 DepartmentHead）
  form.DepartmentHead = row.DepartmentHead || ""; // 处理可能不存在的情况
  // 编制人数（OrgData 中的 quota 是 number，需转为字符串）
  form.authorizedStaffCount = row.authorizedStaffCount;
  // 在职人数（OrgData 中的 staff 是 number，需转为字符串）
  form.activeStaffCount = row.activeStaffCount;

  editDialogVisible.value = true;
};

// 修改 handleSubmit：新增后端API调用
const handleSubmit = async () => {
  editFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        const submitData = {
          department: form.department,
          typeOfOrganization: form.typeOfOrganization,
          DepartmentHead: form.DepartmentHead,
          authorizedStaffCount: Number(form.authorizedStaffCount),
          activeStaffCount: Number(form.activeStaffCount),
        };
        await updateDepartment(currentEditCode.value, submitData);
        await tabledatas();
        editDialogVisible.value = false;
        editFormRef.value?.resetFields();
        ElMessage.success("编辑成功");
      } catch (error) {
        ElMessage.error("编辑失败，请重试");
        console.error("编辑请求失败:", error);
      }
    }
  });
};

// 递归更新表格数据（确保 staff 字段更新）
// const updateOrgData = (
//   data: OrgData[],
//   targetCode: string,
//   newData: Partial<OrgData>
// ) => {
//   for (const item of data) {
//     if (item.OrganizationCode === targetCode) {
//       // 根据 OrgData 接口，将 name 替换为 department
//       item.department = newData.department!;
//       item.type = newData.type!;
//       item.DepartmentHead = newData.DepartmentHead!;
//       item.authorizedStaffCount = newData.quota!;
//       item.parentOrgName = newData.parentOrgName!;
//       item.activeStaffCount = newData.activeStaffCount!; // 新增：更新在职人数
//       return true;
//     }
//     if (item.children && updateOrgData(item.children, targetCode, newData)) {
//       return true;
//     }
//   }
//   return false;
// };

// 取消弹窗（修改后）
const handleCancel = () => {
  editDialogVisible.value = false;
  // 使用 resetFields 重置表单数据和验证状态
  editFormRef.value?.resetFields();
};

// 搜索相关逻辑（修改重置方法）
const searchName = ref("");

// 修改查询方法（原handleQuery）
const handleQuery = async () => {
  try {
    const res = await getDepartmentsByDepartmentHead(searchName.value);
    tableData.value = res.data;
    ElMessage.success("查询成功");
  } catch (error) {
    ElMessage.error("查询失败，请重试");
    console.error("按部门负责人查询失败:", error);
  }
};

// 修改重置方法：清空输入并重新加载所有数据
const handleReset = async () => {
  searchName.value = ""; // 清空搜索输入
  await tabledatas(); // 重新调用获取所有部门数据的接口
  ElMessage.success("已重置，显示所有数据"); // 添加成功提示
};

// 添加表单Ref
const addFormRef = ref<FormInstance>();

// 添加提交
const handleAddSubmit = async () => {
  addFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        // 字段名与后端统一
        const submitData = {
          department: form1.department,
          typeOfOrganization: form1.typeOfOrganization,
          DepartmentHead: form1.DepartmentHead,
          authorizedStaffCount: Number(form1.authorizedStaffCount),
          activeStaffCount: Number(form1.activeStaffCount),
        };
        await addDepartment(submitData);
        await tabledatas();
        addDialogVisible.value = false;
        addFormRef.value?.resetFields();
      } catch (error) {
        console.error("添加组织失败:", error);
      }
    }
  });
};

// 添加取消
const handleAddCancel = () => {
  addDialogVisible.value = false;
  addFormRef.value?.resetFields();
};
// 引入element-plus提示组件
import { ElMessage, ElMessageBox } from "element-plus";
// 导入删除部门的API（需确保utils/api.js中已定义）

// 删除组织方法
const handleDelete = async (row: OrgData) => {
  try {
    await ElMessageBox.confirm(`确定要删除「${row.department}」吗？`, "删除确认", {
      type: "warning",
      confirmButtonText: "确认",
      cancelButtonText: "取消",
    });
    await deleteDepartment(row.id);
    await tabledatas();
    ElMessage.success("删除成功");
  } catch (error) {
    if (error === "cancel") {
      ElMessage.info("已取消删除");
    } else {
      ElMessage.error("删除失败，请重试");
    }
  }
};

const dialogVisible = ref(false);
const currentRow = reactive<Partial<OrgData>>({});

function showDetail(row: OrgData) {
  Object.assign(currentRow, row);
  dialogVisible.value = true;
}
function showEdit(row: OrgData) {
  Object.assign(currentRow, row);
  dialogVisible.value = true;
}
function saveEdit() {
  // 保存逻辑
  dialogVisible.value = false;
}

// 分页相关
const currentPage = ref(1);
const pageSize = ref(5);
const pagedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return tableData.value.slice(start, end);
});
function handleSizeChange(val: number) {
  pageSize.value = val;
  currentPage.value = 1;
}
function handlePageChange(val: number) {
  currentPage.value = val;
}
</script>

<style scoped>
.search-bar,
.action-buttons {
  margin-bottom: 16px;
}

/* 移动端适配 */
@media (max-width: 1000px) {
  .search-bar,
  .action-buttons {
    margin-bottom: 8px;
  }
  .search-bar .el-input {
    width: 120px !important;
    font-size: 13px;
  }
  /* 表格横向滚动容器 */
  .table-scroll-x {
    overflow-x: auto;
    max-width: 100vw;
  }
  .el-table {
    font-size: 12px !important;
    min-width: 700px;
  }
  .el-table th,
  .el-table td {
    padding: 4px 6px !important;
  }
  .el-button {
    margin-right: 4px !important;
    font-size: 13px !important;
    padding: 4px 8px !important;
  }
  .el-dialog {
    width: 95vw !important;
    min-width: unset !important;
    max-width: 100vw !important;
  }
  /* 操作列按钮一行显示不换行，强制flex横向排列 */
  .el-table td .el-table__cell {
    display: flex !important;
    flex-direction: row !important;
    align-items: center;
    gap: 4px;
    white-space: nowrap !important;
  }
  .el-table td .el-button {
    margin-right: 0 !important;
  }
}

.mobile-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px #f0f1f2;
  margin-bottom: 12px;
  padding: 12px 16px;
}
.mobile-row {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}
.mobile-label {
  color: #888;
  min-width: 60px;
  font-size: 14px;
}
.mobile-actions {
  margin-top: 8px;
  gap: 8px;
}
.mobile-actions .el-button {
  margin-right: 8px;
}
.mobile-actions .delete-button > span {
  color: #fff;
  background-color: #f56c6c;
  border-color: #f56c6c;
}
.pagination {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 16px;
}
.mobile-pagination {
  overflow-x: auto;
  padding-bottom: 4px;
}

.dialog-footer-right {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  width: 100%;
}

:deep(.el-pagination .el-pager li) {
  color: #203a64;
}
:deep(.el-pagination .el-pager li.is-active) {
  background: #203a64 !important;
  color: #fff !important;
  border-radius: 4px;
}
:deep(.el-select-dropdown__item) {
  color: #203a64;
}
:deep(.el-select-dropdown__item.selected) {
  background: #203a64 !important;
  color: #fff !important;
}
</style>
